package com.example.handler;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * 拦截器
 * 
 * @author lli
 *
 * @version 1.0
 *
 */
public class MyHandshakeInterceptor implements HandshakeInterceptor {

    // 初次握手访问前 即连接时
    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
            ServerHttpResponse serverHttpResponse,
            WebSocketHandler webSocketHandler, Map<String, Object> map)
        throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest()
                    .getSession(true);
            if (session != null) {
                // 使用userName区分WebSocketHandler，以便定向发送消息
                Object temp = session.getAttribute("user");
                if (temp != null) {
                    map.put("user", temp); // 存入数据，方便在hander中获取
                } else { // 有session ，但是又没有user信息。就是游客
                    String user = "游客";
                    map.put("user", user);
                    session.setAttribute("user", user);
                }
            }
        }
        return true;
    }

    // 初次握手访问后
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse,
            WebSocketHandler webSocketHandler, Exception e) {

    }
}